package cn.wsn2018.tools.service;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.dao.SystemConfigDao;
import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.MySessionContext;
import cn.wsn2018.tools.model.SystemConfig;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: tools
 * @description
 * @author: songDaisong
 * @create: 2020-01-02 20:52
 **/
@Service
public class SecUserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private SystemConfigDao systemConfigDao;

    private static final Logger logger = LoggerFactory.getLogger(SecUserService.class);

    public String getSecUserById(String id,String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 根据用户id查询用户信息
        * @Param: [id] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/20 22:28
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        User secUser = userDao.getSecUserById(id);
        if(secUser!=null){
            JSONObject jsonObject = JSONObject.fromObject(secUser);
            MySessionContext myc= MySessionContext.getInstance();
            HttpSession session = myc.getSession(token);
            String myUsername = session.getAttribute("username").toString();
            LogUtil.produceLogs(myUsername,CommonValue.SELECTED_TYPE,"查询用户名为"+secUser.getUsername()+"的信息",CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
            return JsonUtil.successJson(CommonValue.USER_QUERY_SUCCESS,jsonObject,null);
        }else{
            return JsonUtil.failedJson(CommonValue.USER_QUERY_FAILED);
        }
    }

    public String checkUsernameAvailable(String username,String token,HttpServletRequest request) throws Exception {
       /**
       * @Description:  检查用户名是否可用
       * @Param: [username]
       * @return: java.lang.String
       * @Author: SongDaisong
       * @Date:  2020/1/5 15:18
       */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        User user = userDao.getUserByName(username);
        if(user==null){
            return JsonUtil.successJson(CommonValue.JSON_USERNAME_AVAILABLE,null,null);
        }else{
            return JsonUtil.failedJson(CommonValue.JSON_USERNAME_EXIST);
        }

    }

    public String save(String username,User user,String token,HttpServletRequest request) throws Exception {
        /**
        * @Description:  保存新增用户
        * @Param: [user]
        * @return: java.lang.String
        * @Author: SongDaisong
        * @Date:  2020/1/5 15:11
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(StringUtil.isEmptyString(user.getUsername())
                ||StringUtil.isEmptyString(user.getRole())
                ||StringUtil.isEmptyString(user.getIdCard())
                ||StringUtil.isEmptyString(user.getPhone())
                ||(user.getType()==null)
                ||(user.getAccessTime()==null)
        ){
            //缺少必填信息
            LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,
                    CommonValue.CREATE_USER_LOGINFO+":"+user.getUsername(),
                    CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_USERINFO_NULL);
        }

        //对用户基本信息进行后端校验

        //身份证号
        String idCard_regex="(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9x]$)|" +
                "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)"; //验证18位身份证的正则表达式
        Pattern idCardPattern= Pattern.compile(idCard_regex);//模式
        Matcher idCardMatcher=idCardPattern.matcher(user.getIdCard());//适配器

        //手机号码
        String phone_regex="^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";// 验证手机号
        Pattern phonePattern = Pattern.compile(phone_regex);
        Matcher phoneMatcher = phonePattern.matcher(user.getPhone());

        //ip地址
        String ip_regex = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern ipPattern = Pattern.compile(ip_regex);
        Matcher ipMmatcher = ipPattern.matcher(user.getIpAddress());

        if((!idCardMatcher.matches())||
                (!phoneMatcher.matches())||
                ((!CommonValue.ROLE_ADMIN.equals(user.getRole()))&&(!CommonValue.ROLE_AUDITOR.equals(user.getRole()))&&(!CommonValue.ROLE_SYS_AUDITOR.equals(user.getRole()))&&(!CommonValue.ROLE_OPERATOR.equals(user.getRole())))||
                (user.getType()!=0&&user.getType()!=1)||
                ((user.getType()!=0)&&(user.getType()!=1)&&(user.getType()!=2)&&(user.getType()!=3))){
            LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,
                    CommonValue.CREATE_USER_LOGINFO+":"+user.getUsername()+",角色为:"+RoleUtil.getRoleName(user.getRole()),
                    CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            System.out.println("id-res:"+idCardMatcher.matches());
            return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
        }

        if(!StringUtil.isEmptyString(user.getIpAddress())){
            //如果ip地址不为空，进行判断
            if(!ipMmatcher.matches()){
                LogUtil.produceLogs(username,
                        CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+user.getUsername()+",角色为:"+RoleUtil.getRoleName(user.getRole()),
                        CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
            }
        }


        //将身份证号里面的X或x都转换为小写
        user.setIdCard(user.getIdCard().toLowerCase());

        //设置用户初始密码
        user.setPassword(
                EncryptUtil.md5Encrypt(EncryptUtil.md5Encrypt("Wsn"+user.getIdCard().substring(
                        user.getIdCard().length()-6,
                        user.getIdCard().length())
                        +"scuwsn")+(user.getUsername()+"wsn405").substring(0,7)));

        //账号是否锁定(连续登录失败多次) 0-未锁定 1-锁定
        user.setLock(CommonValue.USER_UNLOCK);

        //账号状态 0-已经注销 1-休眠 2-激活
        user.setState(CommonValue.STATE_ACTIVE);

        //新建账号  默认未授权(1)
        user.setPermission(CommonValue.NO_PERMISSION);

        //上次登录的时间
        user.setLastTime(null);
        //上次密码修改时间
        user.setPwdUpdateTime(null);

        //创建时间
        user.setCreateTime(DateUtil.dateToString(new Date()));

        if(userDao.saveUser(user)) {
            LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+user.getUsername()+",角色为:"+RoleUtil.getRoleName(user.getRole()),
                    CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
            return JsonUtil.successJson(CommonValue.JSON_CREATE_USER_SUCCESS,null,null);
        }else{
            LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+user.getUsername()+",角色为:"+RoleUtil.getRoleName(user.getRole()),
                    CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
        }

    }

    public String listSecUsers(String pageNum,String pageSize,String role,String type,String state,String username,
                               String lock,String permission,
                               String token,HttpServletRequest request,Boolean click) throws Exception {
        /**
        * @Description: 查询所有的符合条件的用户
        * @Param: []
        * @return: java.lang.String
        * @Author: SongDaisong
        * @Date:  2020/1/5 16:23
        */
        //用户角色判断
        String res = null;
            res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        //获取发出操作的用户名
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(token);
        String myUsername = session.getAttribute("username").toString();

        List<User> users = userDao.listSecUsers(pageNum, pageSize,role,type,state,username,lock,permission);

        //查出来的用户 还可能出现最后登录的最先登出，这样的话会造成离线用户在前面
        //因此 用另外个list来转换，在线用户头插法，离线用户尾插法
        LinkedList<User> resUsers=new LinkedList<>();

        if(users.size()>0){
            Map<String,String> onlineUserMap= StorageUtil.getInstance().getLoginSessions();
            logger.info(onlineUserMap.toString());
            for(User u:users){
                //遍历这十个用户
                u.setPassword(null);
                if(onlineUserMap.containsKey(u.getUsername())){
                    u.setOnline(1);
                    resUsers.addFirst(u);
                }
                else{
                    u.setOnline(0);
                    resUsers.addLast(u);
                }
            }
            users=null; //GC
            //logger.info("users:"+users);
            JSONArray jsonArray = JSONArray.fromObject(resUsers);

            //统计符合条件的用户数
            Long resCount = userDao.countSecUsers(role, type, state, username,lock,permission);
            //统计在线人数
            int onlineNums = StorageUtil.getInstance().getLoginSessions().size();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resCount",resCount);
            jsonObject.put("resArray",jsonArray);
            jsonObject.put("onlineNums",onlineNums);
            if(click){
                //用户点击了搜索，需记录日志
                LogUtil.produceLogs(myUsername,CommonValue.SELECTED_TYPE,"查询用户列表",CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
            }
            return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
        }else{
            //users.size()==0
            if(Integer.parseInt(pageNum)==1){
                //当前条件下查询第一页数据都为null，表示无符合此条件的数据
                return JsonUtil.successJson(CommonValue.JSON_NO_ANY_DATA,null,null);
            }else{
                //查询的不是第一页，至少表示之前页有数据
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }

        }

    }

    public String removeSecUserById(String id,String username,String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 注销用户
        * @Param: [id, username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/25 23:33
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        //先判断是否存在此用户
        User secUserById = userDao.getSecUserById(id);
        if(secUserById!=null){
            if(userDao.removeSecUserById(id)){
                LogUtil.produceLogs(username,CommonValue.DELETE_TYPE,CommonValue.DELETE_USER+":"+userDao.getSecUserById(id).getUsername(),
                        CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.USER_REMOVE_SUCCESS,null,null);
            }else{
                LogUtil.produceLogs(username,CommonValue.DELETE_TYPE,CommonValue.DELETE_USER+":id为"+id,
                        CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_REMOVE_FAILED);
            }
        }else{
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.DELETE_USER+":id为"+id+"的用户不存在",
                    CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_UNLOCK_FAILED);
        }
    }

    public String activeSecUserById(String id,String username,String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 激活用户
        * @Param: [id, username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/26 17:30
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        //先判断是否存在此用户
        User secUserById = userDao.getSecUserById(id);
        if(secUserById!=null){
            if(userDao.activeSecUserById(id)){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.ACTIVE_USER+":"+userDao.getSecUserById(id).getUsername(),
                        CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.USER_ACTIVE_SUCCESS,null,null);
            }else{
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.ACTIVE_USER+":id为"+id,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_ACTIVE_FAILED);
            }
        }else{
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.ACTIVE_USER+":id为"+id+"的用户不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_UNLOCK_FAILED);
        }

    }

    //单独做日志
    public String lockSecUserById(String id,String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 锁定用户
        * @Param: [id, token, request] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/2/4 18:09
        */ 
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        //前端无法主动锁定用户，因此只能是定时任务触发锁定用户
        if(userDao.lockSecUserById(id)){
            return JsonUtil.successJson(CommonValue.USER_LOCK_SUCCESS,null,null);
        }else{
            return JsonUtil.failedJson(CommonValue.USER_LOCK_FAILED);
        }
    }

    public String unlockSecUserById(String id,String username,String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 解锁用户
        * @Param: [id, username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/26 17:24
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        //先判断是否存在此用户
        User secUserById = userDao.getSecUserById(id);
        if(secUserById!=null){
            if(userDao.unlockSecUserById(id)){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.UNLOCK_USER+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.USER_UNLOCK_SUCCESS,null,null);
            }else{
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.UNLOCK_USER+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_UNLOCK_FAILED);
            }
        }else{
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.UNLOCK_USER+":id为"+id+"的用户不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_UNLOCK_FAILED);
        }
    }

    public String givePermissionSecUserById(String id,String username,String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 授权
        * @Param: [id,username]
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/26 17:36
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        //先判断是否存在此用户
        User secUserById = userDao.getSecUserById(id);
        if(secUserById!=null){
            if(userDao.givePermissionSecUserById(id)){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_GIVEN_PERMISSION+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.USER_GIVEN_PERMISSION_SUCCESS,null,null);
            }else{
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_GIVEN_PERMISSION+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_GIVEN_PERMISSION_FAILED);
            }
        }else{
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_GIVEN_PERMISSION+":id为"+id+"的用户不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_GIVEN_PERMISSION_FAILED);
        }

    }

    public String removePermissionSecUserById(String id,String username,String token,HttpServletRequest request) throws Exception {
        /**
        * @Description: 移除用户权限
        * @Param: [id, username, token, request]
        * @return: java.lang.String
        * @Author: SongDaisong
        * @Date:  2020/4/13 20:18
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        //先判断是否存在此用户
        User secUserById = userDao.getSecUserById(id);
        if (secUserById!=null){
            if (userDao.removePermissionSecUserById(id)){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_REMOVE_ERMISSION+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.USER_REMOVE_PERMISSION_SUCCESS,null,null);
            }else{
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_REMOVE_ERMISSION+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_REMOVE_PERMISSION_FAILED);
            }
        }else {
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_REMOVE_ERMISSION+":id为"+id+"的用户不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_REMOVE_PERMISSION_FAILED);
        }
    }

    public String resetSecUserPasswordByid(String id, String username, String token, HttpServletRequest request) throws Exception {
        /** 
        * @Description: 重置密码
        * @Param: [id, username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/26 18:00
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        User secUserById = userDao.getSecUserById(id);
        if(secUserById!=null){
            int resVal = userDao.resetSecUserPasswordByid(id);
            if(resVal==0){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_RESET_PWD+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.USER_RESET_PWD_SUCCESS,null,null);
            }else if(resVal==-1){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_RESET_PWD+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_RESET_PWD_FAILED_USER_NULL);
            }else if(resVal==1){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_RESET_PWD+":"+secUserById.getUsername()+","+CommonValue.USER_RESET_PWD_FAILED_USER_ID_NULL,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_RESET_PWD_FAILED_USER_ID_NULL);
            }else{
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_RESET_PWD+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_RESET_PWD_FAILED);
            }
        }else{
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_RESET_PWD+":id为"+id+"的用户不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_RESET_PWD_FAILED);
        }
    }

    public String updateSecUserInfo(String id,String idCard,String phone,
                                    String role,Integer type,Integer accesssTime,String ipAddress,String username,
                                    String token,HttpServletRequest request) throws Exception {
        /** 
        * @Description: 修改用户信息
        * @Param: [id, idCard, phone, role, type, accesssTime, ipAddress, username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/1/26 18:09
        */
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        User secUserById = userDao.getSecUserById(id);
        if(secUserById==null){
            //根据id并未查到此用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_INFO_UPDATE+":id为"+id+"的用户不存在",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_INFO_UPDATE_FAILED);
        }

        //后端校验
        //判断空
        if(StringUtil.isEmptyString(id)||StringUtil.isEmptyString(phone)||StringUtil.isEmptyString(idCard)||StringUtil.isEmptyString(role)||
                (accesssTime==null||type==null)){
            //ip地址可以为空
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_INFO_UPDATE+":缺少必填用户信息",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_INFO_UPDATE_FAILED);
        }

        //身份证号
        String idCard_regex="(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9x]$)|" +
                "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)"; //验证18位身份证的正则表达式
        Pattern idCardPattern= Pattern.compile(idCard_regex);//模式
        Matcher idCardMatcher=idCardPattern.matcher(idCard);//适配器

        //手机号码
        String phone_regex="^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";// 验证手机号
        Pattern phonePattern = Pattern.compile(phone_regex);
        Matcher phoneMatcher = phonePattern.matcher(phone);

        //ip地址
        String ip_regex = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern ipPattern = Pattern.compile(ip_regex);
        Matcher ipMmatcher = ipPattern.matcher(ipAddress);

        if((!idCardMatcher.matches())||
                (!phoneMatcher.matches())||
                ((!CommonValue.ROLE_ADMIN.equals(role))&&(!CommonValue.ROLE_AUDITOR.equals(role))&&(!CommonValue.ROLE_SYS_AUDITOR.equals(role))&&(!CommonValue.ROLE_OPERATOR.equals(role)))||
                (type!=0&&type!=1)||
                ((accesssTime!=0)&&(accesssTime!=1)&&(accesssTime!=2)&&(accesssTime!=3))){
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_INFO_UPDATE+":提交用户信息格式不规范",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_INFO_UPDATE_FAILED);
        }

        if(!StringUtil.isEmptyString(ipAddress)){
            //如果ip地址不为空，进行判断
            if(!ipMmatcher.matches()){
                LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_INFO_UPDATE+":ip地址不规范",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.USER_INFO_UPDATE_FAILED);
            }
        }

        if(userDao.updateSecUserInfo(id,idCard.toLowerCase(),phone,role,type,accesssTime,ipAddress)){
            //修改成功
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,"修改用户名为"+secUserById.getUsername()+"的基本信息",CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
            return JsonUtil.successJson(CommonValue.USER_INFO_UPDATE_SUCCESS,null,null);
        }else{
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.USER_INFO_UPDATE+":"+secUserById.getUsername(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.USER_INFO_UPDATE_FAILED);
        }


    }

    public String updateSystemConfig(SystemConfig systemConfig,String username,String token,HttpServletRequest request) throws Exception {

        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        //后端对系统配置进行校验

        //判断是否是纯数字
        String num_regex="[0-9]{1,}";
        Pattern pattern = Pattern.compile(num_regex);
//        if((!pattern.matcher(systemConfig.getNotLoginTime()).matches())||
//                (!pattern.matcher(systemConfig.getPwdValidTime()).matches())||
//                (!pattern.matcher(systemConfig.getAccountValidTime()).matches())||
//                (!pattern.matcher(systemConfig.getLockedTime()).matches())||
//                (!pattern.matcher(systemConfig.getLoginFailedNum()).matches())||
//                (!pattern.matcher(systemConfig.getSessionMaxOverTime()).matches())||
//                (!pattern.matcher(systemConfig.getLogMaxVolume()).matches())||
//                (!pattern.matcher(systemConfig.getConcurrentMaxNum()).matches())){
//            //只要一个不是纯数字，则返回失败
//            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":参数格式不规范",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
//            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
//        }

        //是纯数字后再转换

        //int notLoginTime = Integer.parseInt(systemConfig.getNotLoginTime());
        int pwdValidTime = Integer.parseInt(systemConfig.getPwdValidTime());
        int accountValid = Integer.parseInt(systemConfig.getAccountValidTime());
        int loginFailedNum = Integer.parseInt(systemConfig.getLoginFailedNum());
        int lockTime = Integer.parseInt(systemConfig.getLockedTime());
        int sessionTime = Integer.parseInt(systemConfig.getSessionMaxOverTime());
        int logMaxVolume = Integer.parseInt(systemConfig.getLogMaxVolume());
        int concurrentMaxNum = Integer.parseInt(systemConfig.getConcurrentMaxNum());

//        if(notLoginTime<1){
//            //未登录时间间隔不能小于1
//            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":未登录时间间隔不能小于1",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
//            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
//        }

        if(pwdValidTime<1||pwdValidTime>90){
            //密码有效期为1-90天
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":密码有效期应为为1-90天",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

        if(accountValid<1||accountValid>90){
            //临时账户有效期最长为90
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":临时账户有效期应为为1-90天",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

        if(loginFailedNum<1||loginFailedNum>10){
            //登录失败的次数在1-10之间
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":登录失败的次数在1-10之间",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

        if(lockTime<20){
            //锁定时间不能小于20分钟
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":锁定时间不能小于20分钟",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

        if(sessionTime<1||sessionTime>30){
            //会话session时间在1-30之间
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":会话session时间在1-30之间",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

        if(concurrentMaxNum<1){
            //并发数不能小于1
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":并发数不能小于1",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

        if(logMaxVolume<1){
            //日志容量至少为1g
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG+":日志容量至少为1G",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }


        if(systemConfigDao.updateSystemConfig(systemConfig)){
            //数据库更新成功了才设置
            SystemConfig config=systemConfig;
            //根据系统管理员配置来设置会话超时时间
            Integer sessionOutOfTime=Integer.parseInt(config.getSessionMaxOverTime());
            //增加系统会话超时时间
            CommonValue.SESSION_OUT_OF_TIME=sessionOutOfTime*60;
            logger.info("SessionMaxOverTime："+CommonValue.SESSION_OUT_OF_TIME+",config Time:"+sessionOutOfTime);
            HttpSession session=request.getSession(true);
            session.setMaxInactiveInterval(CommonValue.SESSION_OUT_OF_TIME);

            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG,CommonValue.LOG_TYPE_SYS,CommonValue.SUCCESS);
            return JsonUtil.successJson(CommonValue.SYSTEM_CONFIG_SUCCESS,null,null);
        }else{
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.SYSTEM_CONFIG,CommonValue.LOG_TYPE_SYS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.SYSTEM_CONFIG_FAILED);
        }

    }

    public String getSystemConfig(String token,HttpServletRequest request) throws Exception {
        //用户角色判断
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_ADMIN,CommonValue.ADMIN_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        SystemConfig systemConfig = systemConfigDao.getSystemConfig();
        if(systemConfig!=null){
            JSONObject jsonObject = JSONObject.fromObject(systemConfig);
            return JsonUtil.successJson(CommonValue.GET_SYSTEM_CONFIG_SUCCESS,jsonObject,null);
        }else {
            return JsonUtil.failedJson(CommonValue.GET_SYSTEM_CONFIG_FAILED);
        }
    }

    public void setSecUserLastLoginTime(String id){
        /** 
        * @Description: 用户最新的登录时间 
        * @Param: [id] 
        * @return: void 
        * @Author: SongDaisong 
        * @Date:  2020/1/28 16:41
        */ 
        userDao.setLastLoginTime(id);
    }

    /**
     * 直接获取SystemConfig的Java对象，方便判断时使用
     * @return
     */
    public SystemConfig getStorageSystemConfig(){
        SystemConfig systemConfig = systemConfigDao.getSystemConfig();
        return systemConfig;
    }


    public String getAuthorizationState(String username) {
        /** 
        * @Description: 获取用户此时授权状态
        * @Param: [username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/2/13 15:53
        */ 
        User user = userDao.getUserByName(username);
        if(user!=null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("permissionState",user.getPermission());
            return JsonUtil.successJson(CommonValue.JSON_AUTHORIZATION_SUCCESS,jsonObject,null);
        }else{
            return JsonUtil.failedJson(CommonValue.JSON_AUTHORIZATION_FAILED);
        }

    }

    public String askPermissionSecUserByName(String username) {
        /** 
        * @Description: 用户请求授权
        * @Param: [username] 
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/2/3 16:47
        */ 
        User user = userDao.getUserByName(username);
        if(user==null){
            //用户名无对应用户
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,username+CommonValue.JSON_ASK_AUTHORIZED+";"+CommonValue.JSON_USERNAME_NOTEXIST,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_USERNAME_NOTEXIST);
        }
        if(userDao.askPermissionSecUserByName(username)){
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,CommonValue.JSON_ASK_AUTHORIZED,CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
            return JsonUtil.successJson(CommonValue.JSON_ASK_AUTHORIZED_SUCCESS,null,null);
        }else{
            LogUtil.produceLogs(username,CommonValue.UPDATE_TYPE,username+CommonValue.JSON_ASK_AUTHORIZED,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.successJson(CommonValue.JSON_ASK_AUTHORIZED_FAILED,null,null);
        }
    }

    public void produceUrlWarningLog(String username, String urlPathname, HttpServletRequest httpServletRequest) {
        /**
        * @Description:  处理前端url复制产生的越权问题
        * @Param: [username, urlPathname, httpServletRequest]
        * @return: void
        * @Author: SongDaisong
        * @Date:  2020/2/4 16:00
        */

        User user = userDao.getUserByName(username);
        System.out.println("^^^"+user.toString());
        if(user==null){
            //用户不存在
            return;
        }

        //系统审计员页面
         final String systemAuditor="systemAuditor";
         //设计员页面
         final String auditor="auditor";
        //系统管理员页面
         final String admin="admin";

         //操作员页面 else里面就是操作员
        //final String operator="index";

         if(urlPathname.contains(systemAuditor)){
             //再次判断用户角色真的不对
             if(!CommonValue.ROLE_SYS_AUDITOR.equals(user.getRole())){
                 String msg = LogUtil.produceUrlWarningMsg(username, RoleUtil.getRoleName(user.getRole()), CommonValue.SYS_AUDITOR_MODULE);
                 LogUtil.produceWarningLogs(username,
                         CommonValue.WARNING_TYPE_1,
                         CommonValue.WARNING_LEVEL_0,
                         CommonValue.SYS_AUDITOR_MODULE,
                         ServletUtil.getClientIp(httpServletRequest),
                         msg);
             }
         }else if(urlPathname.contains(auditor)){
             if(!CommonValue.ROLE_AUDITOR.equals(user.getRole())){
                 String msg = LogUtil.produceUrlWarningMsg(username, RoleUtil.getRoleName(user.getRole()), CommonValue.AUDITOR_MODULE);
                 LogUtil.produceWarningLogs(username,
                         CommonValue.WARNING_TYPE_1,
                         CommonValue.WARNING_LEVEL_0,
                         CommonValue.AUDITOR_MODULE,
                         ServletUtil.getClientIp(httpServletRequest),
                         msg);
             }
         }else if(urlPathname.contains(admin)){
             if(!CommonValue.ROLE_ADMIN.equals(user.getRole())){
                 String msg = LogUtil.produceUrlWarningMsg(username, RoleUtil.getRoleName(user.getRole()), CommonValue.ADMIN_MODULE);
                 LogUtil.produceWarningLogs(username,
                         CommonValue.WARNING_TYPE_1,
                         CommonValue.WARNING_LEVEL_0,
                         CommonValue.ADMIN_MODULE,
                         ServletUtil.getClientIp(httpServletRequest),
                         msg);
             }
         }else{
             //排除外系统审计员、系统管理员、业务审计员，剩下的就是操作员
             if(!CommonValue.ROLE_OPERATOR.equals(user.getRole())){
                 String msg = LogUtil.produceUrlWarningMsg(username, RoleUtil.getRoleName(user.getRole()), CommonValue.OPERATOR_MODULE);
                 LogUtil.produceWarningLogs(username,
                         CommonValue.WARNING_TYPE_1,
                         CommonValue.WARNING_LEVEL_0,
                         CommonValue.OPERATOR_MODULE,
                         ServletUtil.getClientIp(httpServletRequest),
                         msg);
             }
         }
    }

    public String getSleepUserOverYear(){
        /**
        * @Description: 当前休眠用户是否有快到期间
        * @Param: []
        * @return: int
        * @Author: SongDaisong
        * @Date:  2020/4/13 21:08
        */
        Integer count = userDao.isHasSleepUserWillOverYear();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count",count);
        return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
    }


    public String isOneline(String token, String username) {
        /** 
        * @Description: 判断用户是否在线 
        * @Param: [token, username]
        * @return: java.lang.String 
        * @Author: SongDaisong 
        * @Date:  2020/5/1 13:28
        */

        HttpSession session = MySessionContext.getInstance().getSession(token);

        Map<String, String> map = StorageUtil.getInstance().getLoginSessions();

        String msg=null;
        if (session==null || !username.equals(session.getAttribute("username"))){
            //session为空 或者 用户名不相等
            map.remove(username);   //移除对应的用户信息
            msg="offline";
        }else{
            msg="online";
            SystemConfig config = SystemConfig.getInstance();
            Integer sessionOutOfTime=Integer.parseInt(config.getSessionMaxOverTime());
            session.setMaxInactiveInterval(sessionOutOfTime*60);
        }

        return JsonUtil.successJson(msg, null, null);
    }
}
